﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BidFunLib.Entity;
using System.Windows.Forms;

namespace BidFunLib.BidWeb
{
    /// <summary>
    /// Class for login
    /// </summary>
    public class BidWebLogin
    {
        /// <summary>
        /// Perform the login account ?
        /// </summary>
        public bool EnableLogin { get; set; }

        BidLogin login;

        public BidLogin Login
        {
            get { return login; }
            set { login = value; }
        }

        HtmlElement husername;
        HtmlElement hpassword;
        HtmlElement hbutton_submit;
        public HtmlElement bid_credits_left;

        public BidWebLogin()
        {
            EnableLogin = true;
        }

        public BidWebLogin(BidLogin login, bool enable)
        {
            Login = login;
            EnableLogin = enable;
        }

        public Boolean CheckForLogin(HtmlDocument doc)
        {
            if (EnableLogin)
            {
                husername = doc.GetElementById("username");
                hpassword = doc.GetElementById("password");
                hbutton_submit = doc.GetElementById("submit");

                if (husername != null && hpassword != null && hbutton_submit != null)
                {
                    return true;
                }
                return false;
            }
            else
            {
                return true;
            }
        }

        public Boolean DoLogin(HtmlDocument doc)
        {
            if (EnableLogin == true && CheckForLogin(doc) == true)
            {
                if (husername != null && hpassword != null)
                {
                    husername.InnerText = Login.Name;
                    hpassword.InnerText = Login.Password;
                    hbutton_submit.InvokeMember("click");
                    return true;
                }
                return false;
            }
            else
            {
                return true;
            }
        }

        public Boolean isLoged(HtmlDocument doc)
        {
            bid_credits_left = doc.GetElementById("bid_credits_left");
            if (bid_credits_left != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public void logOut(HtmlDocument doc)
        {
            foreach (HtmlElement item in doc.Links)
            {
                if (item.OuterHtml != null && item.OuterHtml.Contains("/bin/logout"))
                {
                    item.InvokeMember("click");
                    return;
                }
            }
        }
    }
}
